<template>
  <el-dialog title="角色分配" :visible="showRoleDialog" @close="btnCancel">
    <el-checkbox-group v-model="roleIds">
      <!-- el-checkbox 中的label是选择的值 -->
      <el-checkbox
        v-for="item in roleList"
        :key="item.id"
        :label="item.id"
      >{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <el-row slot="footer" type="flex" justify="center" align="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnOk">确认</el-button>
        <el-button size="small" @click="btnCancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getRoleList } from '@/api/settings'
import { getUserDetailById } from '@/api/user'
// 给员工分配角色的接口
import { assignPerm } from '@/api/employees'
export default {
  name: 'AssginRole',
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      required: true,
      default: null
    }
  },
  data() {
    return {
      roleList: [], // 存储获取的所有角色
      roleIds: [] // 管理当前员工拥有的角色id
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { rows } = await getRoleList({ page: 1, pagesize: 20 })
      this.roleList = rows
    },
    async getUserDetailById(id) {
      // 由于props是异步传值 当弹窗出现的时候id还没有传过来所有 不能使用props的userId
      // 因为 我们是想在弹层出现的时候多选框就默认勾选 所有只能用父调子方法传值
      const { roleIds } = await getUserDetailById(id)
      this.roleIds = roleIds
    },
    async btnOk() {
      await assignPerm({ id: this.userId, roleIds: this.roleIds })
      this.$emit('update:showRoleDialog', false)
    },
    async btnCancel() {
      this.$emit('update:showRoleDialog', false)
    }
  }
}

</script>

<style>

</style>
